package service

import (
	"CartApp/common"
	"CartApp/dao/mysql"
	"CartApp/models"
	"CartApp/pkg/e"
	"CartApp/serializer"

	logging "github.com/sirupsen/logrus"
)

func Register(register *models.UserService) *serializer.Response {
	code := e.SUCCESS
	var user models.User
	var count int
	mysql.DB.Debug().Model(&models.User{}).
		Where("user_name = ?", register.UserName).
		First(&user).Count(&count)
	//表单验证
	if count == 1 {
		code = e.ErrorExistUser
		return &serializer.Response{
			Status: code,
			Msg:    e.GetMsg(code),
		}
	}
	user.UserName = register.UserName
	//加密密码
	password, err := common.SetPassword(register.Password)
	if err != nil {
		logging.Info("common.SetPassword", err)
		code = e.ErrorFailEncryption
		return &serializer.Response{
			Status: code,
			Msg:    e.GetMsg(code),
		}
	}
	user.PasswordDigest = password
	//创建用户
	if err := mysql.DB.Create(&user).Error; err != nil {
		logging.Info(err)
		code = e.ErrorDatabase
		return &serializer.Response{
			Status: code,
			Msg:    e.GetMsg(code),
		}
	}
	return &serializer.Response{
		Status: code,
		Msg:    e.GetMsg(code),
	}
}
